<?php
/*
 * Service基类
 */
declare(strict_types=1);

namespace Libraries\Bases;

use Swoole\Server;

abstract class ServiceBase
{
    protected $intFd;
    protected $intReactorId;

    /**
     * 构造函数
     * @param int $intFd
     * @param int $intReactorId
     */
    public function __construct(int $intFd = -1, int $intReactorId = -1)
    {
        $this->intFd = $intFd;
        $this->intReactorId = $intReactorId;
    }
    
    /**
     * 按Token分配WorkerID
     * @global Server $objTcpServer
     * @param string $strToken
     * @param int|null $intWorkerNum
     * @return int|null
     */
    public static function getWorkerIdByToken(string $strToken, ?int $intWorkerNum = null): ?int
    {
        $re = null;
        if (!$intWorkerNum) {
            global $objTcpServer;
            $objTcpServer && $intWorkerNum = $objTcpServer->setting['worker_num'];
        }
        if ($intWorkerNum) {
            $intWorkerId = ceil(hexdec(substr($strToken, 0, 3)) / 4096 * $intWorkerNum);
            $intWorkerId >= $intWorkerNum && $intWorkerId = 0;
            $re = intval($intWorkerId);
        }
        return $re;
    }
}
